package com.lsismo.core.base.action;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.lsismo.core.base.util.Constants;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class BaseAction extends ActionSupport implements Preparable {

    private static final long serialVersionUID = 1L;

  /*  protected ServletContext servletContext;

    protected HttpServletRequest httpServletRequest;

    protected HttpServletResponse httpServletResponse;
    
    protected HttpSession httpSession;
    
    protected Map<String, Object> session;

    public void setServletContext(ServletContext context) {
	this.servletContext = context;
    }
    
    public void setServletResponse(HttpServletResponse response) {
	this.httpServletResponse = response;
    }

    public void setServletRequest(HttpServletRequest request) {
	this.httpServletRequest = request;
	this.httpSession = request.getSession();
    }

    public void setSession(Map<String, Object> session) {
	this.session = session;
    }*/
    
    
    /**
	 * 保存当前登录用户信息的线程变量
	 */
//	public static ThreadLocal<User> LoginUser = new ThreadLocal<User>();
	
	/**
	 * 保存当前登录用户信息的线程变量
	 */
	public void prepare() throws Exception {
		
		//onLineValidation();
	}

    /**
     * 将消息保存到session中，如果已经存在则附加在后面
     * @param msg 放到session中的消息
     */
    @SuppressWarnings("unchecked")
    protected void saveMessage(String msg) {
        List messages = (List) getRequest().getSession().getAttribute("messages");
        if (messages == null) {
            messages = new ArrayList();
        }
        messages.add(msg);
        getRequest().getSession().setAttribute("messages", messages);
    }

    /**
     * 从servlet上下文中获得配置信息HashMap
     *
     * @return 用户放入session中的属性
     */
    @SuppressWarnings("unchecked")
	protected Map getConfiguration() {
        Map config = (HashMap) getSession().getServletContext().getAttribute(Constants.CONFIG);
        
        if (config == null) {
            return new HashMap();
        }
        return config;
    }

    /**
     * 获得请求(HttpServletRequest对象）
     * @return 当前请求
     */
    protected HttpServletRequest getRequest() {
		
        return ServletActionContext.getRequest();
    }

    /**
     * 获得响应（HttpServletRequest对象）
     * @return 当前响应current response
     */
    protected HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }
    
    /**
     * 输出Json数据
     * @param json
     * @throws IOException
     */
    protected void print(String json) throws IOException {
    	this.getResponse().setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
    	this.getResponse().setHeader("Pragma", "no-cache");
    	this.getResponse().addHeader("Content-Encoding", "gzip");
    	this.getResponse().setContentType(("text/html"));//("text/json");
    	this.getResponse().setCharacterEncoding("utf-8");
    	this.getResponse().getWriter().print(json);
    	this.getResponse().getWriter().close();
    }

	/**
	 * 产生CODE
	 * code = 首字母 + 6位时间 + 5位随机数
	 * update by xiejian
	 * @param String str
	 * @throws ParseException
	 */
	public static String generateCode(String initial) {
		StringBuffer sb = new StringBuffer();
		Random rd = new Random();
		int rdGet; // 取得随机数
		char ch;
		for (int i = 0; i < 5; i++) {
			//产生97到122的随机数(a-z的键位值)
			rdGet = Math.abs(rd.nextInt()) % 26 + 97; 
            ch = (char) rdGet;
            sb.append(ch);
		}
		Calendar cal = new GregorianCalendar();
		SimpleDateFormat theDate = new SimpleDateFormat("yyMMddHHmmss");
		String dateString = theDate.format(cal.getTime());
		initial = initial==null?"":initial;
		
	    return initial + dateString + sb.toString();
	}
	
    /**
     * 获得Session（HttpSession对象），如果session不存在则创建一个新的session
     * @return 从Request中获得的Session
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }

    /*public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }*/


    
    
}
